package com.example.studentims.controller;

import com.example.studentims.service.PhotoPathProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api")
public class TreeController {

    @Autowired
    private PhotoPathProvider photoPathProvider;

    @GetMapping("/tree")
    public Map<String, List<Map<String, String>>> getTree(@RequestParam(value = "path", defaultValue = "") String path) throws IOException {
        path = URLDecoder.decode(path, StandardCharsets.UTF_8);
        Path basePath = photoPathProvider.getPhotoPath();
        Path targetPath = path.isBlank() ? basePath : photoPathProvider.resolve(path);

        if (!Files.exists(targetPath) || !Files.isDirectory(targetPath)) {
            return Map.of("folders", List.of(), "files", List.of());
        }

        List<Map<String, String>> folders = Files.list(targetPath)
                .filter(Files::isDirectory)
                .map(p -> {
                    Path rel = basePath.relativize(p);
                    String relPath = rel.toString().replace("\\", "/");
                    return Map.of("name", p.getFileName().toString(), "path", relPath);
                }).collect(Collectors.toList());

        List<Map<String, String>> files = Files.list(targetPath)
                .filter(Files::isRegularFile)
                .map(p -> {
                    Path rel = basePath.relativize(p);
                    String relPath = rel.toString().replace("\\", "/");
                    return Map.of(
                            "name", p.getFileName().toString(),
                            "url", "/photos/" + relPath,
                            "path", relPath
                    );
                }).collect(Collectors.toList());

        return Map.of("folders", folders, "files", files);
    }

    @PostMapping("/upload")
    public ResponseEntity<String> upload(@RequestParam("file") MultipartFile file,
                                         @RequestParam("targetDir") String targetDir) {
        try {
            String decodedDir = URLDecoder.decode(targetDir, StandardCharsets.UTF_8);
            Path targetPath = decodedDir.isBlank()
                    ? photoPathProvider.getPhotoPath()
                    : photoPathProvider.resolve(decodedDir);

            if (!Files.exists(targetPath)) {
                Files.createDirectories(targetPath);
            }

            Path destination = targetPath.resolve(file.getOriginalFilename());
            file.transferTo(destination.toFile());

            return ResponseEntity.ok("上传成功");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("上传失败：" + e.getMessage());
        }
    }

    @DeleteMapping("/delete")
    public String delete(@RequestBody Map<String, String> request) throws IOException {
        String relPath = request.get("path");
        if (relPath == null) return "路径不能为空";

        Path target = photoPathProvider.resolve(relPath);
        if (!Files.exists(target)) return "文件/文件夹不存在";

        if (Files.isDirectory(target)) {
            // 递归删除
            Files.walk(target)
                    .sorted(Comparator.reverseOrder())
                    .forEach(p -> {
                        try {
                            Files.delete(p);
                        } catch (IOException e) {
                            throw new RuntimeException("删除失败：" + p, e);
                        }
                    });
        } else {
            Files.delete(target);
        }

        return "删除成功";
    }

    @PostMapping("/rename")
    public String rename(@RequestBody Map<String, String> request) throws IOException {
        String oldPath = request.get("oldPath");
        String newName = request.get("newName");

        if (oldPath == null || newName == null) return "参数错误";

        Path oldFullPath = photoPathProvider.resolve(oldPath);
        Path newFullPath = oldFullPath.resolveSibling(newName);

        if (!Files.exists(oldFullPath)) return "原始路径不存在";
        if (Files.exists(newFullPath)) return "新名称已存在";

        Files.move(oldFullPath, newFullPath);
        return "重命名成功";
    }

    @PostMapping("/create-folder")
    public ResponseEntity<String> createFolder(@RequestBody Map<String, String> data) {
        String parentPath = data.getOrDefault("parentPath", "");
        String folderName = data.get("folderName");

        if (folderName == null || folderName.trim().isEmpty()) {
            return ResponseEntity.badRequest().body("文件夹名称不能为空");
        }

        Path fullPath = parentPath.isBlank()
                ? photoPathProvider.getPhotoPath().resolve(folderName)
                : photoPathProvider.resolve(parentPath).resolve(folderName);

        try {
            if (!Files.exists(fullPath)) {
                Files.createDirectories(fullPath);
                return ResponseEntity.ok("文件夹创建成功");
            } else {
                return ResponseEntity.status(HttpStatus.CONFLICT).body("文件夹已存在");
            }
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("创建失败：" + e.getMessage());
        }
    }
}
